package com.ukee.birthday.modules.controller;

import com.ukee.birthday.common.utils.R;
import com.ukee.birthday.modules.entity.StaffEntity;
import com.ukee.birthday.modules.form.SysLoginForm;
import com.ukee.birthday.modules.service.StaffService;
import com.ukee.birthday.modules.service.SysUserTokenService;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.Map;

/**
 * 登录相关
 */
@RestController
public class SysLoginController extends AbstractController{

//    @Autowired
//    private SysUserService sysUserService;

    @Autowired
    private SysUserTokenService sysUserTokenService;

    @Autowired
    private StaffService staffService;

    private final static int EXPIRE = 3600 * 12;

    /**
     * 登录
     */
    @PostMapping("/sys/login")
    public Map<String,Object>login(@RequestBody SysLoginForm form) throws IOException {
        logger.info("login api,SysLoginForm={}",form);
        StaffEntity user = null;
//        StaffEntity user = staffService.queryByUserName(form.getUsername());
        if(form.getUsername().equals("admin")){
            user = staffService.queryByUserName(form.getUsername());
        }else {
            user = staffService.queryByTel(form.getUsername());
        }
        logger.info("login api,user={}",user);

        //账号不存在、密码错误
        if(user == null){
            return R.error("账号不存在！");
        }else {
            if(!user.getPassword().equals(new Sha256Hash(form.getPassword(),user.getSalt()).toHex())){
                return R.error("密码不正确");
            }
        }

        if(user.getRoleId() != 1){
            return R.error("当前账号不是管理员！");
        }

        //生成token，保存到数据库
        R r = sysUserTokenService.createToken(user.getId(),1);
        return r;
    }

    @PostMapping("sys/logout")
    public R logout(){
        sysUserTokenService.logout(getUserId());
        return R.ok();
    }

}
